import {defineStore} from "pinia";
import {ref, reactive, computed} from 'vue'
import {setToken, getToken, clearToken} from "@/utils/auth.js";
import {login, logout, getUserInfo} from "@/apis/auth/login/index.js";
import {message} from "ant-design-vue";

export const useUserStore = defineStore({
    id: "user",
    state: () => ({
        token: getToken() || "",
        userInfo: {},
    }),
    getters: {},
    actions: {
        /** 重置token */
        resetToken() {
            this.token = "";
            clearToken();
        },
        /** 登录 */
        async accountLogin(data) {
            try {
                const res = await login(data);
                if (res.code === 200) {
                    setToken(res.data.token);
                    this.token = res.data.token;
                    message.success(res.message);
                    return Promise.resolve(res.code);
                } else {
                    message.error(res.message);
                }
            } catch (error) {
                message.error(error.message);
            }
        },
        /** 退出登录 */
        accountLogout() {
            try {
                logout().then(res => {
                    if (res.code === 200) {
                        this.logoutCallBack();
                    }
                });
                return Promise.resolve(true);
            } catch (error) {
                return Promise.resolve(false);
            }
        },
        /** 退出登录回调 */
        logoutCallBack() {
            this.resetToken();
        },
        /** 获取用户信息 */
        getUserInfo() {
        }
    },
    persist: {
        paths: [],
        storage: localStorage,
    }
});